﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace NKD07.Admin
{
    public partial class manage_product : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategory();
                LoadProductList();
            }
        }

        // load and show all name of categories in database
        private void LoadCategory()
        {
            Classes.category category = new Classes.category();
            DataTable tb =  category.getAllCategories();
            dlCaregories.DataSource = tb;
            dlCaregories.DataBind();
        }

        private void LoadProductList()
        {
            string strCategoryID = Request.QueryString["categoryID"];
            int intCategoryID = -1;
            try
            {
                intCategoryID = int.Parse(strCategoryID);
            }
            catch (Exception)
            {
                intCategoryID = -1;
            }
            Classes.product product = new Classes.product();
            DataTable tb =  product.GetProductsByCategoryID(intCategoryID, 0);
            gvProducts.DataSource = tb;
            gvProducts.DataBind();

        }

        protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex < 0) return;
            if (e.Row.RowIndex != gvProducts.EditIndex)
            {
                ((ImageButton)e.Row.Cells[8].FindControl("imgbtnDelete")).Attributes.Add("onclick", "return confirm('do you want to delete this products?')");
            }
        }

        // delete informations of product in databse
        private bool DeleteProductByID(int productID)
        {
            Classes.product product = new Classes.product();
            bool result = product.DeleteProductByID(productID);
            return result;
        }

        protected void gvProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int productID = int.Parse(gvProducts.DataKeys[e.RowIndex].Value.ToString());
                bool result = DeleteProductByID(productID);
                if (result == false)
                    e.Cancel = true;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
            LoadProductList(); 
        }

        protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string productID = gvProducts.DataKeys[e.NewEditIndex].Value.ToString();
            Response.Redirect("edit_product.aspx?productID="+productID);
        }

    }
}